package net.aiion.weave.impl.web.service.http;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.aiion.weave.spi.web.service.WeaveService;
import net.aiion.weave.spi.web.service.WeaveServiceException;
import net.aiion.weave.spi.web.service.WeaveServiceRequest;
import net.aiion.weave.spi.web.service.WeaveServiceResponse;

public class WeaveServiceRunner implements Runnable
{
    private static final Logger LOGGER = Logger.getLogger(WeaveServiceRunner.class.getName());

    private final AsyncContext asyncContext;

    public WeaveServiceRunner(final AsyncContext aAsyncContext) {
        asyncContext = aAsyncContext;
    }

    @Override
    public void run() {
        try {
            final HttpServletRequest httpServletRequest = (HttpServletRequest) asyncContext.getRequest();
            final HttpServletResponse httpServletResponse = (HttpServletResponse) asyncContext.getResponse();

            final WeaveServiceRequest weaveServiceRequest = new WeaveServiceRequestImpl(httpServletRequest);
            final WeaveServiceResponse weaveServiceResponse = new WeaveServiceResponseImpl(httpServletResponse);
            final WeaveService weaveService = new WeaveServiceImpl(weaveServiceRequest, weaveServiceResponse);

            switch (httpServletRequest.getMethod()) {
            case "POST":
                weaveService.doPost();
                break;
            case "GET":
                weaveService.doGet();
                break;
            default:
                throw new WeaveServiceException("Unsupported method " + httpServletRequest.getMethod());
            }
        } catch (final WeaveServiceException e) {
            LOGGER.log(Level.SEVERE, "Unexpected exception occured", e);
        } finally {
            asyncContext.complete();
        }
    }
}
